package com.xxx.car.service.impl;

import com.xxx.car.entity.TbRedpacketRecord;
import com.xxx.car.entity.TbRedpacketRecordExample;
import com.xxx.car.entity.TbRedpacketRule;
import com.xxx.car.entity.TbRedpacketRuleExample;
import com.xxx.car.mapper.TbRedpacketRecordMapper;
import com.xxx.car.mapper.TbRedpacketRuleMapper;
import com.xxx.car.service.RedpacketService;
import com.xxx.car.service.UserWalletService;
import com.xxx.common.base.vo.APIResponse;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Isolation;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;

import java.math.BigDecimal;
import java.text.DecimalFormat;
import java.util.List;
import java.util.Random;

/**
 * Created by youxiaojia on 2017/6/21.
 */
@Service
public class RedpacketServiceImpl implements RedpacketService {

    private final static Logger logger = LoggerFactory.getLogger(UserServiceImpl.class);

    @Autowired
    TbRedpacketRecordMapper tbRedpacketRecordMapper;
    @Autowired
    TbRedpacketRuleMapper tbRedpacketRuleMapper;
    @Autowired
    UserWalletService userWalletService;

    @Override
    @Transactional(propagation = Propagation.REQUIRED, isolation = Isolation.REPEATABLE_READ, rollbackFor = Exception.class)
    public APIResponse snatchRedpacket(Integer travelOrderId, Integer userId) {
        boolean flag = this.canSnatchRedpacket(travelOrderId);
        if (!flag) {
            return APIResponse.returnFail("已经抢过红包,下次再来吧");
        }
        BigDecimal amount = this.createAmount();
        if (amount == null){
            return APIResponse.returnFail("手气不好,再接再励");
        }
        TbRedpacketRecord tbRedpacketRecord = new TbRedpacketRecord();
        tbRedpacketRecord.setTravelOrderId(travelOrderId);
        tbRedpacketRecord.setUserId(userId);
        tbRedpacketRecord.setAmount(amount);
        tbRedpacketRecord.setStatus((byte)0);
        int result = tbRedpacketRecordMapper.insertSelective(tbRedpacketRecord);
        if (result < 1){
            logger.error("插入红包记录失败.travelOrderId:{},userId{},amount{}",travelOrderId,userId,amount);
            return APIResponse.returnFail("手气不好,再接再励");
        }
        try {
            userWalletService.changeAmt(userId,0,amount,0,0);
        } catch (Exception e) {
            logger.error("抢红包充值资产失败.travelOrderId:{},userId{},amount{}",travelOrderId,userId,amount);
            throw e;
        }
        return APIResponse.returnSuccess(amount);
    }

    @Override
    public boolean canSnatchRedpacket(Integer travelOrderId) {
        TbRedpacketRecordExample tbRedpacketRecordExample = new TbRedpacketRecordExample();
        TbRedpacketRecordExample.Criteria criteria = tbRedpacketRecordExample.createCriteria();
        criteria.andTravelOrderIdEqualTo(travelOrderId);
        int count = tbRedpacketRecordMapper.countByExample(tbRedpacketRecordExample);
        if (count == 0) {
            return true;
        }
        return false;
    }

    private BigDecimal createAmount(){
        TbRedpacketRuleExample tbRedpacketRuleExample = new TbRedpacketRuleExample();
        TbRedpacketRuleExample.Criteria criteria = tbRedpacketRuleExample.createCriteria();
        criteria.andIsEnableEqualTo((byte)1);
        List<TbRedpacketRule> tbRedpacketRules = tbRedpacketRuleMapper.selectByExample(tbRedpacketRuleExample);
        if (CollectionUtils.isEmpty(tbRedpacketRules)){
            return null;
        }
        byte ruleType = tbRedpacketRules.get(0).getRuleType();
        if (ruleType == (byte)1) {
            return new BigDecimal(tbRedpacketRules.get(0).getDefaultValue());
        } else if (ruleType == (byte)2) {
            double Min = tbRedpacketRules.get(0).getMinValue();
            double Max = tbRedpacketRules.get(0).getMaxValue();
            Random random = new Random();
            //精确小数点2位
            DecimalFormat formatter = new DecimalFormat("#.##");
            //随机一个数，数值范围在最小值与最大值之间
            String money = formatter.format(random.nextDouble() * (Max - Min) + Min);
            return new BigDecimal(money);
        }
        return null;
    }



    public static void main(String[] args){

    }

}
